<?php


namespace app\index\controller;

use Cassandra\Varint;
use http\Params;
use think\admin\Controller;
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use AlibabaCloud\Tea\Tea;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Console\Console;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use GatewayClient\Gateway;
use app\data\service\IotThingService;
use app\data\service\OtaService;
use app\data\model\DataDeviceSettings;
use app\data\model\DataDevice;
use app\data\model\DataCat;
use app\data\model\DataCatLog;
class Test extends Controller
{
    function ext_json_decode($str, $mode=true){
        if(preg_match('/\w:/', $str)){
            $str = preg_replace('/(\w+):/is', '"$1":', $str);
        }
        $str;
    }
    function test11(){
        $json='["P","r","o","d","u","c","t","K","e","y",":","k","0","7","6","y","Y","5","O","M","D","X",",","D","e","v","i","c","e","N","a","m","e",":","M","e","o","w","1","1","9",",","D","e","v","i","c","e","S","e","c","r","e","t",":","a","5","1","6","6","5","8","b","4","f","6","5","8","2","4","1","b","5","b","6","f","4","f","9","b","8","7","a","e","2","0","d"]
';
        $json_arr=json_decode($json,true);
        $json_str = join("",$json_arr);
        $arr = explode(',',$json_str);
        $new_arr = [];
        foreach($arr as $v){
            $arr_a = explode(':',$v);
            $new_arr[$arr_a[0]]=$arr_a[1];
        }
        print_r($new_arr);
        echo $new_arr['ProductKey'];
        echo $new_arr['DeviceName'];
        exit;
        $arr = array('Hello','World!','Beautiful','Day!');
        echo join("",$arr);exit;
        $str = 'ProductKey:k076yY5OMDX,DeviceName:Meow119,DeviceSecret:b242ac5054232af8ad1f43af45d8a84d';
        $arr = explode(',',$str);
        $new_arr = [];
        foreach($arr as $k =>$v){
            $arr_a = explode(':',$v);
            $new_arr[$arr_a[0]]=$arr_a[1];
        }
        echo  $new_arr['ProductKey'];
        print_r($new_arr);exit;
        $json ='{"deviceType":"CustomCategory","iotId":"vYGyYca8ARjALtee1qrIk076y0","requestId":"1718608928000","checkFailedData":{},"productKey":"k076yY5OMDX","gmtCreate":1718608929345,"deviceName":"Meow119","items":{"Light":{"value":{"Time1_Not_Disturb_Off_M":36,"B":50,"Time1_Not_Disturb_On_M":35,"Brightness":38,"Time1_Not_Disturb_Off_H":13,"Mode":2,"G":35,"Time2_Not_Disturb_On_H":15,"Switch1_Not_Disturb":0,"Switch2_Not_Disturb":0,"Time_Toggle":6,"Time2_Not_Disturb_On_M":30,"R":150,"Time2_Not_Disturb_Off_H":11,"Switch":1,"Time2_Not_Disturb_Off_M":30,"Switch_Toggle":0,"Time1_Not_Disturb_On_H":13},"time":1718608929341}}}
';
        $data = json_decode($json,true);

        if(isset($data['items'])) {
            $arr = $data['items'];
            $title = key($arr);
            $value = $data['items'][$title]['value'];
            if(isset($value['Mode'])){
                $arr = [
                    '1'=>'科技蓝',
                    '2'=>'科技粉',
                    '3'=>'科技白',
                    '4'=>'薄荷绿',
                    '5'=>'紫罗兰',
                    '6'=>'清新黄',
                    '7'=>'毒液绿',
                    '8'=>'粉紫色',
                    '9'=>'冰湖蓝',
                    '10'=>'自定义颜色',
                ];
                $remark =  '灯光切换为'.($arr[$value['Mode']]);
                $log_data=[
                    'iot_id'=>$data['iotId'],
                    'remark'=>$remark
                ];
                print_r($log_data);
            }
        }

        exit;
        $weight=4.73;
        echo 4730;
        $weight_setting = sysconf('about.weight_min_max');
        $start_weight = $weight*1000-$weight_setting;
        $end_weight = $weight*1000+$weight_setting;
        $cat = DataCat::mk()->where(['member_id'=>1,'is_deleted'=>0])
            ->where('weight','between',[$start_weight,$end_weight])->select()->toArray();
        print_r($cat);
        $count  = count($cat);
        if($count == 1){
            return $cat[0]['id'];
        }elseif($count == 0){
            return 0;
        }else{
            foreach($cat as $k=>$v){
                $cat[$k]['abs']=abs($weight*1000-$v['weight']);
            }
            $minAge = min(array_column($cat, 'abs'));
            $minColumn = array_reduce($cat, function($carry, $item) use ($minAge) {
                if ($item['abs'] === $minAge) {
                    return $item;
                }
                return $carry;
            });
            return $minColumn['id'];
        }
    }
    function getTotalData($cat_id,$days_array){
        $res=[];
        foreach($days_array as $k=> $v){
            $res[$k] =  DataCatLog::mk()->whereDay('in_time',$v)->count();
        }
        return $res;

    }
    function test(){
        $sort = DataCat::mk()->where(['member_id'=>1,'is_deleted'=>0])
            ->order('sort asc')
            ->group('sort')->having('sort > 0')
            ->column('sort');
        $array=[1,2,3,4,5,6,7,8];
        $missing=[];
        foreach($array as $v){
            if(!in_array($v, $sort)){
                $missing[] = $v;
            }
        }
        $sort = empty($missing)?0:min($missing);
        echo $sort;
        exit;
        $days=90;
        $days_array = getLastSevenDays($days); //获取近期日期数量
        $startTime = date('Y-m-d H:i:s', strtotime('-'.$days.' days')); // $days天前的开始时间
        $endTime = date('Y-m-d H:i:s'); // 当前时间
        $cats = DataCatLog::mk()->alias('l')->join('data_cat c','c.id = l.cat_id')
            ->where('in_time', '>=', $startTime)
            ->where('in_time', '<=', $endTime)
            ->where('cat_id', '>', 0)
            ->group('cat_id')
            ->column('cat_id,nickname');
        $res=[];
        foreach($cats as $k =>$v){
            $res[$k]['name']=$v['nickname'];
            $res[$k]['data']=$this->getTotalData($v['cat_id'],$days_array);
        }
        print_r($res);
        exit;
        $array = [
            ['name' => 'Alice', 'age' => 25],
            ['name' => 'Bob', 'age' => 20],
            ['name' => 'Charlie', 'age' => 22]
        ];

// 假设我们要找到age字段的最小值所对应的列
        $minAge = min(array_column($array, 'age'));

// 使用array_reduce找到包含最小age的列
        $minColumn = array_reduce($array, function($carry, $item) use ($minAge) {
            if ($item['age'] === $minAge) {
                return $item;
            }
            return $carry;
        });

        print_r($minColumn);
        exit;
        //1709793343972
        //1709793343971
        $date = new \DateTime('2024-03-07 14:35:43.971');
        $timestamp = $date->getTimestamp() * 1000 + $date->format('u') / 1000;
        echo $timestamp;exit;
        $code =config('errorcode.warning');
        var_dump($code[-2]);exit;
        $json = '{
    "Security_Level":{
        "value":2,
        "time":1705026252653
    },
    "Switch_Screen_Light":{
        "value":1,
        "time":1705026252653
    },
    "Switch_Drive":{
        "value":0,
        "time":1705026252653
    },
    "Door_State":{
        "value":0,
        "time":1705026252653
    },
    "Clean":{
        "value":{
            "Time_Not_Disturb_Off_M":22,
            "Time_Not_Disturb_Off_H":22,
            "Timing_Clean_Switch5":1,
            "Timing_Clean_Switch3":1,
            "Timing_Clean_Switch4":1,
            "Timing_Clean_Switch1":1,
            "Timing_Clean_Switch2":1,
            "Switch_Not_Disturb":1,
            "Timing_Clean_Time2_H":22,
            "Timing_Clean_Time1_H":22,
            "Switch":0,
            "Timing_Clean_Time4_H":22,
            "Timing_Clean_Time3_H":22,
            "Time_Not_Disturb_On_H":22,
            "Timing_Clean_Time1_M":22,
            "Timing_Clean_Time5_H":22,
            "Timing_Clean_Time3_M":22,
            "Timing_Clean_Time2_M":22,
            "Timing_Clean_Time5_M":22,
            "Time_Delay":22,
            "Time_Not_Disturb_On_M":22,
            "Timing_Clean_Time4_M":22
        },
        "time":1705026252653
    },
    "Litter_Species":{
        "value":1,
        "time":1705026252653
    }
}';
        $arr = json_decode($json,true);
        DataDeviceSettings::mk()->setting('HcOc6p6EanF20EdXGVv6k076y0',$arr);

    }
    //获取OTA升级信息
    public function get_ota(){
        $otaObj = new OtaService();
        $data=[
            'deviceName'=>'dev_3',
            'productKey'=>'a1IgvsxtKcy',
            'taskStatus'=>'CONFIRM'
        ];
        $res = $otaObj->listUnfinishedTask($data);
        $this->success('获取成功',$res);
    }
    //确认升级
    public function confirmupdate(){
        $otaObj = new OtaService();
        $data=[
            "taskId" => [
                "Ss2eQSjWcvVYXfwot5cE010100"
            ]
        ];
        $res = $otaObj->confirmUpdate($data);
        $this->success('获取成功',$res);
    }
    //推送
    public function push(){
        $otaObj = new OtaService();
        $data=[
            "jobId"=>"VqzbQ6FHz0mSeuwNWTbL020200",
            "taskId" => [
                "9VgYMW8SzyUhzekxkc3W010100"
            ]
        ];
        $res = $otaObj->pushTask($data);
        $this->success('获取成功',$res);
    }
    public function index()
    {
        $ip = '116.2.178.190';
        $ip2region = new \Ip2Region();
        $info = $ip2region->memorySearch($ip);
        $res = explode('|',$info['region']);
        echo $res[3];
        exit;
    }
    public function send(){
        if(Gateway::isUidOnline(3)){
            Gateway::sendToUid(3, 'i am back');
        }
    }
    //获取设备属性快照
    public function getPro(){
        $class = new IotThingService();
        $data=[
            'iotId'=>'HcOc6p6EanF20EdXGVv6k076y0',//设备IOTid
            "iotInstanceId" => "iot-06z00e8bap0eq65"
        ];
        $res = $class->getProp($data);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                echo $response->body->code;
            }else{
              $json = json_encode($response->body->data->list->propertyStatusInfo);
              $data = json_decode($json,true);//属性列表arr
              print_r($data);
            }
        }else{
            $this->error($res['data']);
        }
    }
    //设置设备属性
    public function setPro(){
        $class = new IotThingService();
        $iotId='HcOc6p6EanF20EdXGVv6k076y0';
        $item = '{"Sterilize":{"Switch":1}}';
        $res = $class->setProp($iotId,$item);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                echo $response->body->code;
            }else{
                echo $response->body->data->messageId;
            }
        }else{
            $this->error($res['data']);
        }
    }
    //调用服务
    public function setSer(){
        $class = new IotThingService();
        $title = 'Calibrate_Litter'; //服务标题
        $iot_id = 'HcOc6p6EanF20EdXGVv6k076y0';
        $res = $class->setService($iot_id,$title);
        if($res['err_code'] == 0){
            $response = $res['data'];
            if($response->body->code !=''){
                echo $response->body->code;
            }else{
                var_dump($response->body->data->result);
            }
        }else{
            $this->error($res['data']);
        }
    }
}
